package personnel.department.pages.widgets.combo;

import static personnel.department.dao.HibernateUtils.getSession;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.hibernate.Query;
import org.hibernate.Session;

import com.google.common.collect.Lists;

import personnel.department.pages.widgets.AbstractWidget;


public abstract class AbstractComboWidget extends AbstractWidget<String> {

	private String title;
	private Composite parent;
	private Label label;
	private CCombo combo;

	public AbstractComboWidget(Composite parent,  String title, Field field) {
		super(field);
		this.parent = parent;
		this.title = title;
		create();
	}

	@Override
	protected void create() {
		label = new Label(parent, SWT.NONE);
		label.setText(title);
		combo = new CCombo(parent, SWT.BORDER);
		GridDataFactory.swtDefaults().indent(0, 10).hint(160, 20).applyTo(combo);
		combo.addListener(SWT.Modify, event -> modify());
		combo.setItems(getItemsByHql(null, Collections.emptyMap()));
		super.create();
	}
	
	public void addTraverseAction(Listener listener) {
		combo.addListener(SWT.Traverse, listener);
	}
	
	
	public void addSelectionAction(Listener listener) {
		combo.addListener(SWT.Selection, listener);
	}

	private String[] getItemsByHql(String hql, Map<String, Object> params) {
		Session session = getSession();
		Query query = session.createQuery(hql == null ? getHql() : hql);
		params.keySet().stream().forEach(key -> query.setParameter(key, params.get(key)));
		List<String> result = query.list();
		result.add("");
		return result.toArray(new String[0]);
	}

	protected abstract String getHql();

	@Override
	public void setValue(String value) {
		combo.setText(value);
		modify();
	}

	@Override
	public String getValue() {
		return combo.getText();
	}
	
	@Override
	protected Control getWidget() {
		return combo;
	}
	
	public void setItems(String hql, Map<String, Object> params) {
		combo.setItems(getItemsByHql(hql, params));
	}

}
